/*
 * Copyright (c) Huawei Device Co., Ltd. 2024. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ef_ac_main.h"

#include "common_utils.h"
#include "der_parser.h"
#include "loghelper.h"

namespace OHOS {
namespace SE {
std::vector<uint8_t> g_arfRefreshTag {};

EfAcMain::EfAcMain(const std::vector<uint8_t> &path)
    : EfParser()
{
    acMainPath_ = path;
}

EfAcMain::~EfAcMain()
{
}

std::vector<uint8_t> EfAcMain::ParseAcMainFileData(const std::vector<uint8_t> &fileData)
{
    std::shared_ptr<DerParser> der = std::make_shared<DerParser>(fileData);
    der->GetTlvDataLength(ASN1_SEQUENCE);
    if (der->GetTlvDataLength(ASN1_OCTET_STRING) != REFRESHTAG_LEN) {
        ErrorLog("RefreshTag length invalid");
        return std::vector<uint8_t>();
    }

    std::vector<uint8_t> refreshTag = der->GetTlvData();

    std::string refreshTagInChip = CommonUtils::BytesArrayToHexString(&refreshTag[0], refreshTag.size());
    InfoLog("refreshTagInChip:%{public}s", refreshTagInChip.c_str());
    if (g_arfRefreshTag != refreshTag) {
        g_arfRefreshTag = refreshTag;
        InfoLog("Need Refresh buffer!");
        std::string refreshTagInCache = CommonUtils::BytesArrayToHexString(&g_arfRefreshTag[0], g_arfRefreshTag.size());
        InfoLog("refreshTagInCache:%{public}s", refreshTagInCache.c_str());
        return der->ParseEfPath();
    }
    return std::vector<uint8_t>();
}

std::vector<uint8_t> EfAcMain::ParseAcMainFileByPath()
{
    InfoLog("Parsing AC MAIN file by path");
    uint16_t rspApdu = 0;
    if (!ReadFileByPath(acMainPath_, rspApdu)) {
        ErrorLog("fail to read ac main file, rspApdu[%{public}x]", rspApdu);
        return std::vector<uint8_t>();
    }
    std::vector<uint8_t> acMainFileData = ReadFileByDataSize(0, -1);
    return ParseAcMainFileData(acMainFileData);
}
}  // namespace SE
}  // namespace OHOS
